using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace BlogSystem.Web.Filters
{
    public class CtmActionFilterAttribute : Attribute, IActionFilter
    {
        public IMemoryCache Cache { get; set; }
        public CtmActionFilterAttribute(IMemoryCache cache)
        {
            Cache = cache;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if(context.ActionArguments.ContainsKey("token"))
            {
                //获取Token值
                var token = context.ActionArguments["token"].ToString();
                var hasValue = Cache.TryGetValue(token, out object value);
                if (hasValue)
                {
                    context.HttpContext.Items.Add("loginSuccessInfo", value);
                    Cache.Set(token, value, TimeSpan.FromMinutes(5));
                }
                else
                {
                    // 短路器
                    context.Result = new JsonResult(null){
                        StatusCode = 203
                    };
                }
            }


        }
    }
}